package com.utils;

import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.Instant;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.TreeSet;
import java.util.concurrent.ThreadLocalRandom;
import java.util.stream.Collectors;

import cn.hutool.core.util.ObjectUtil;
import com.zbkj.crmeb.express.model.ShippingTemplates;
import com.zbkj.crmeb.express.service.ShippingTemplatesService;
import com.zbkj.crmeb.store.dto.product.StoreProductQueryDTO;
import com.zbkj.crmeb.store.model.*;
import com.zbkj.crmeb.store.service.*;
import org.apache.commons.codec.digest.DigestUtils;
import org.dom4j.DocumentException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Lazy;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.constants.Constants;
import com.crmeb.core.config.MybatisPlusConfig;
import com.crmeb.core.config.RestTemplateConfig;
import com.crmeb.core.utils.TableNameUtil;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JavaType;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.github.pagehelper.util.StringUtil;
import com.zbkj.crmeb.chant.model.ChannelMerchant;
import com.zbkj.crmeb.chant.service.IChannelMerchantService;
import com.zbkj.crmeb.enums.BarCodeEnum;
import com.zbkj.crmeb.enums.OrangeChannelTypeEnum;
import com.zbkj.crmeb.enums.ProductTypeEnum;
import com.zbkj.crmeb.enums.StockAreaTempEnum;
import com.zbkj.crmeb.front.response.BuyerProductResDTO;
import com.zbkj.crmeb.front.response.BuyerProductResDTO.Product;
import com.zbkj.crmeb.front.response.BuyerProductResDTO.ProductSku;
import com.zbkj.crmeb.front.service.ProductService;
import com.zbkj.crmeb.store.dto.ImItemResDTO;
import com.zbkj.crmeb.store.dto.ImItemResDTO.ImItemDTO;
import com.zbkj.crmeb.store.dto.ImProductInfoResDTO;
import com.zbkj.crmeb.store.dto.ImProductResDTO;
import com.zbkj.crmeb.store.dto.LeamProductResDTO;
import com.zbkj.crmeb.store.dto.XyyProductSkuResDTO;
import com.zbkj.crmeb.store.dto.XyyProductSkuResDTO.TStorhouse;
import com.zbkj.crmeb.system.model.SystemConfig;
import com.zbkj.crmeb.system.service.SystemConfigService;

import cn.hutool.core.codec.Base64;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.map.MapUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.digest.DigestUtil;
import lombok.extern.slf4j.Slf4j;
import net.logstash.logback.encoder.org.apache.commons.lang.StringUtils;

/**
 * 远程商品查询相关操作
 * @Description: 
 * @author daigb
 * @date 2021-03-12
 */
@Slf4j
@Component
public class ProductUtil {
    @Autowired
    RestTemplateUtil restTemplateUtil;
    @Autowired
    RestTemplateConfig restTemplateConfig;
    @Autowired
    EuropeUtil europeUtil;
    @Lazy
    @Autowired
    private ProductService productService;
    @Autowired
    private StoreProductService storeProductService;
    @Autowired
    SystemConfigService systemConfigService;
    @Autowired
    private SupplierService supplierService;
    @Autowired
    private IChannelMerchantService channelMerchantService;
    @Autowired
    @Lazy
    private StoreProductMerService storeProductMerService;
    @Autowired
    private ChannelCategoryConfigService channelCategoryConfigService;

    @Autowired
    private ShippingTemplatesService shippingTemplatesService;

    @Autowired
    private StoreProductAttrValueService storeProductAttrValueService;

    @Autowired
    private StoreProductValueMerService storeProductValueMerService;

    /********* buyer配置参数 *********/
    @Value("${buyer.url}")
    private String buyUrl;
    @Value("${buyer.appkey}")
    private String buyAppKey;
    @Value("${buyer.appsecret}")
    private String buyAppSecret;

    /********* europe配置参数  *********/
    @Value("${europe.url}")
    private String europeUrl;
    @Value("${europe.username}")
    private String europeUsername;
    @Value("${europe.password}")
    private String europePassword;
    private final String xmlGetGoodsById = "<tem:GetGoodsByGoodsID><tem:GoodsID>{}</tem:GoodsID></tem:GetGoodsByGoodsID>";
    private final String xmlGetGoodsDetailByGoodsID = "<tem:GetGoodsDetailByGoodsID><tem:GoodsID>{}</tem:GoodsID></tem:GetGoodsDetailByGoodsID>";
    
    /********* im配置参数  *********/
    @Value("${im.appKey}")
    private String imAppKey;
    @Value("${im.appSecret}")
    private String imAppSecret;
    @Value("${im.url.domain}")
    private String imDomainUrl;
    @Value("${im.url.goods}")
    private String imGoodsUrl;
    @Value("${im.url.token}")
    private String imTokenUrl;
    @Value("${im.url.skus}")
    private String imSkusUrl;
    @Value("${im.url.category}")
    private String imCategoryUrl;
    @Value("${im.url.brand}")
    private String imBrandUrl;
    @Value("${im.url.info}")
    private String imInfoUrl;
    @Value("${im.url.itemInfo}")
    private String imItemInfoUrl;
    @Value("${im.url.productInfo}")
    private String imProductInfoUrl;


    /********* xyy配置参数  *********/
    @Value("${xyy.appkey}")
    private String xyyAppKey;
    @Value("${xyy.secret}")
    private String xyyAppSecret;
    @Value("${xyy.baseUrl}")
    private String xyyUrl;

    /********* leam配置参数  *********/
    @Value("${leam.url}")
    private String leamUrl;
    @Value("${leam.token}")
    private String leamToken;

    /********* gb配置参数  *********/
    @Value("${gb.url}")
    private String gbUrl;
    @Value("${gb.username}")
    private String gbUsername;
    @Value("${gb.password}")
    private String gbPassword;

    /**
     * 获取商品实时库存
     * @Description:  eur商品(barcode+尺码+buyStock) buyer商品(barcode+sourceSkuId+buyStock) IM商品(barcode+sourceSkuId+buyStock)
     * @author daigb 
     * @param @param barCode 源商品goodsId
     * @param @param color 颜色(欧洲可为空,buyer必传)
     * @param @param size 
     * @param @param buyStock 所需库存
     * @param @return
     * @return Integer
     * @throws
     */
    public Integer getStockByBarCode(String barCode, String sourceSkuId, String size, Integer buyStock) {
        log.info("--------------- 收到实时查询库存接口调用: barcode: {}, sourceSkuId: {}, size: {}, buyStock: {} ---------------", barCode, sourceSkuId, size, buyStock);
        int stock = 0;
        if(StringUtils.isEmpty(barCode) || 4 >= barCode.length() || null == buyStock) {
            return stock;
        }
        String id = barCode.substring(0, 4);
        
        // buyer商品
        if(BarCodeEnum.BUYER == BarCodeEnum.valueOf(Integer.parseInt(id))) {
            stock = this.getBuyerStockByBarCode(barCode, sourceSkuId);
        // 欧洲商品
        } else if(BarCodeEnum.EUROPE == BarCodeEnum.valueOf(Integer.parseInt(id))) {
            stock =  getEuropeStockByBarCode(barCode, size);
        // IM商品
        } else if(BarCodeEnum.IM == BarCodeEnum.valueOf(Integer.parseInt(id))) {
            stock =  getImStockByBarCode(barCode, sourceSkuId,buyStock);
        // 喜洋洋商品
        } else if(BarCodeEnum.XYY == BarCodeEnum.valueOf(Integer.parseInt(id))) {
            stock =  getXyyStockByBarCode(barCode, sourceSkuId);
        }
//        else if(BarCodeEnum.LEAM == BarCodeEnum.valueOf(Integer.parseInt(id))){
//            stock = getLeamStockByBarCode(sourceSkuId);
//        }
        else if(BarCodeEnum.GB == BarCodeEnum.valueOf(Integer.parseInt(id))){
            stock = getGbStockByBarCode(sourceSkuId);
        }
        // 需要更新实时库存商品
        if(buyStock > stock) {
            log.info("--------------- 需要实时更新商品: barcode: {}, sourceSkuId: {}, size: {}, buyStock: {} ---------------", barCode, sourceSkuId, size, buyStock);
            StoreProduct storeProduct = storeProductService.getByBarCode(barCode);
            productService.updateProductByNow(storeProduct);
        }
        
        return stock;
    }

    private int getGbStockByBarCode(String sourceSkuId) {
        String xml = "<soapenv:Envelope xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:urn=\"urn:fDisponibilita\">\n" +
                "   <soapenv:Header/>\n" +
                "   <soapenv:Body>\n" +
                "      <urn:fDisponibilita soapenv:encodingStyle=\"http://schemas.xmlsoap.org/soap/encoding/\">\n" +
                "         <articolo xsi:type=\"xsd:string\">"+sourceSkuId+"</articolo>\n" +
                "         <iguNegozio xsi:type=\"xsd:string\">139</iguNegozio>\n" +
                "         <user xsi:type=\"xsd:string\">"+gbUsername+"</user>\n" +
                "         <password xsi:type=\"xsd:string\">"+gbPassword+"</password>\n" +
                "      </urn:fDisponibilita>\n" +
                "   </soapenv:Body>\n" +
                "</soapenv:Envelope>";
        RestTemplate restTemplate = restTemplateConfig.restTemplate();
        ResponseEntity<String> str = restTemplate.postForEntity(gbUrl, xml, String.class);
        log.info("--------------请求查询库存返回结果:{}-------------",str.getBody());
        try {
            Map<String, Object> map = XmlUtil.parse(str.getBody());
            return (int) map.get("disponibilita");
        } catch (DocumentException e) {
            log.error("--------------请求查询库存失败:{}-------------",str.getBody());
        }
        return 0;
    }

    /**
     * 获取buyer商品数据和详情
     * @Description:  
     * @author daigb 
     * @param @param id 商品barCode
     * @param @return
     * @param @throws Exception
     * @return BuyerProductResDTO
     * @throws
     */
    public BuyerProductResDTO getBuyerProductByBarCode(String barCode) throws Exception {
        if(StringUtils.isEmpty(barCode) || 4 >= barCode.length()) {
            return null;
        }
        String id = barCode.substring(4, barCode.length());
        
        log.info("--------------- 查询buyer远程数据, 商品id: {} ---------------", id);
        String timestamp = String.valueOf(Instant.now().getEpochSecond());
        String random = String.valueOf(ThreadLocalRandom.current().nextInt(1000, 9999));
        String signature = getSignature(timestamp, random);
        Map<String, String> parMap = new HashMap<String, String>();
        parMap.put("appkey", this.buyAppKey);
        parMap.put("appsecret", this.buyAppSecret);
        parMap.put("t", timestamp);
        parMap.put("r", random);
        parMap.put("s", signature);
        parMap.put("op", "goods");
        parMap.put("action", "list");
        parMap.put("goods_ids", id);
        String result = restTemplateUtil.getData(this.buyUrl + "?appkey={appkey}&appsecret={appsecret}&t={t}&r={r}&s={s}&op={op}&action={action}&goods_ids={goods_ids}", parMap);
        log.info("--------------- buyer远程数据返回结果: {} ---------------", result);

        ObjectMapper mapper = new ObjectMapper();
        BuyerProductResDTO buyerProductResDTO = mapper.readValue(result, BuyerProductResDTO.class);

        return buyerProductResDTO;
    }
    
    /**
     * 获取远程Europe商品和详情
     * @Description:  
     * @author daigb 
     * @param @param barCode
     * @param @return
     * @return EuropeProduct
     * @throws
     */
    public EuropeProduct getEuropeByBarCode(String barCode) {
        if(StringUtils.isEmpty(barCode) || 4 >= barCode.length()) {
            return null;
        }
        String id = barCode.substring(4, barCode.length());
        
        try {
            log.info("--------------- 查询Europe商品远程数据, 商品id: {} ---------------", id);
            String auth = Base64.encode((europeUsername + ":" + europePassword).getBytes());
            String msg = EuropeUtil.getSendMsg(StrUtil.format(xmlGetGoodsById, id));
            String respXml = europeUtil.getEuropeXmlNew(auth, europeUrl, msg);
            log.info("--------------- 获取到Europe商品远程数据, 报文为: {} ---------------", respXml);
            if (StringUtil.isEmpty(respXml)) {
                log.info("--------------- 获取到Europe商品远程数据, respXml数据为空:{} ---------------", id);
                return null;
            }
            // 数据提取(获取单个商品数据)
            List<Map<String, Object>> europMapList = STAXUtil.getEuropMapList(respXml, "GetGoodsByGoodsID");
            if (CollectionUtils.isEmpty(europMapList)) {
                log.info("--------------- 获取到Europe商品远程数据, europMapList数据为空:{} ---------------", id);
                return null;
            }
            // 解析主商品
            Map<String, Object> europMap = europMapList.get(0);
            BigDecimal price = new BigDecimal((String) europMap.get("Price"));
            String goodsId = (String) europMap.get("ID");
            EuropeProduct europeGood = new EuropeProduct();
            // 解析商品sku
            List<EuropeProductSku> productSkus = getEuropeProductSkus(goodsId);
            europeGood = getEuropeProduct(europeGood, europMap, price, productSkus);
            europeGood.setNewCreatedTime(DateUtil.date());
            // 解析商品skuMerged
            Map<String, Integer> sumStockMap = productSkus.stream().collect(Collectors.groupingBy(c -> c.getAttrKey(), Collectors.summingInt(EuropeProductSku::getQty)));
            productSkus = productSkus.stream().filter(sku -> StringUtils.isNotBlank(sku.getAttrKey() + sku.getSize())).map(sku -> sku.setQty(sumStockMap.get(sku.getAttrKey()))).collect(Collectors.collectingAndThen(Collectors.toCollection(() -> new TreeSet<>(Comparator.comparing(EuropeProductSku::getAttrKey))), ArrayList::new));
            europeGood.setSkuList(productSkus);
            List<EuropeProductSkuMerged> europeProductSkuMergeds = new ArrayList<EuropeProductSkuMerged>();
            productSkus.forEach(sku -> {
                if (0 < sku.getQty()) {
                    EuropeProductSkuMerged skuMerged = new EuropeProductSkuMerged();
                    skuMerged.setSkuId(sku.getId());
                    skuMerged.setGoodsId(sku.getGoodsId() + "");
                    skuMerged.setStock(sku.getQty());
                    skuMerged.setColor(sku.getColor());
                    skuMerged.setSize(sku.getSize());
                    skuMerged.setUpdateFlag(sku.getUpdateFlag());
                    skuMerged.setCreateTime(sku.getNewCreatedTime());
                    skuMerged.setEditTime(sku.getNewModifyTime());
                    skuMerged.setSuk(sku.getSuk());
                    skuMerged.setCreateTime(new Date());
                    europeProductSkuMergeds.add(skuMerged);
                }
            });

            europeGood.setSkuMergedList(europeProductSkuMergeds);
            return europeGood;
        } catch (DocumentException e) {
            e.printStackTrace();
        }

        return null;
    }
    
    /**
     * 获得Europe商品详情
     * @Description:  
     * @author daigb 
     * @param @param goodsId
     * @param @return
     * @return List<EuropeProductSku>
     * @throws
     */
    public List<EuropeProductSku> getEuropeProductSkus(String goodsId) {
        String auth = Base64.encode((europeUsername + ":" + europePassword).getBytes());
        String sendMsg = EuropeUtil.getSendMsg(StrUtil.format(xmlGetGoodsDetailByGoodsID, goodsId));
        try {
            String respXml = europeUtil.getEuropeXmlNew(auth, europeUrl, sendMsg);
            List<Map<String, Object>> europMapList = STAXUtil.getEuropMapList(respXml, "GetGoodsDetailByGoodsID");

            Map<String, Object> map = europMapList.get(0);
            List<EuropeProductSku> list = new ArrayList<>();
            @SuppressWarnings("unchecked")
            List<HashMap<String, Object>> stockList = (List<HashMap<String, Object>>) map.get("Stock");

            stockList.forEach(item -> {
                EuropeProductSku europeProductSku = new EuropeProductSku();
                int qty = Integer.parseInt((String) item.get("Qty"));
                getEuropeProductSku(qty, europeProductSku, map, item, stockList);
                list.add(europeProductSku);
            });
            return list;
        } catch (Exception e) {
            e.printStackTrace();
        }

        return null;
    }

    // Europe商品构建
    private EuropeProduct getEuropeProduct(EuropeProduct europeGood, Map<String, Object> map, BigDecimal price, List<EuropeProductSku> productSkus) {
        europeGood.setGoodId(Integer.parseInt((String) map.get("ID")));
        europeGood.setModel((String) map.get("Model"));
        europeGood.setVariante((String) map.get("Variante"));
        europeGood.setSeason((String) map.get("Season"));
        europeGood.setCollection((String) map.get("Collection"));
        europeGood.setSupplierId(Integer.parseInt((String) map.get("SupplierID")));
        europeGood.setBrandId(Integer.parseInt((String) map.get("BrandID")));
        europeGood.setParentCategoryId(Integer.parseInt((String) map.get("ParentCategoryID")));
        europeGood.setCategoryId(Integer.parseInt((String) map.get("CategoryID")));
        europeGood.setTypeId(Integer.parseInt((String) map.get("TypeID")));
        europeGood.setCode((String) map.get("Code"));
        europeGood.setGoodsName((String) map.get("GoodsName"));
        europeGood.setReferencePrice(new BigDecimal((String) map.get("ReferencePrice")));
        europeGood.setPrice(price);
        europeGood.setDiscount((String) map.get("Discount"));
        europeGood.setStock(Integer.parseInt((String) map.get("Stock")));
        europeGood.setMainPicNo((String) map.get("MainPicNo"));
        europeGood.setNewModifyTime(DateUtil.date());
        europeGood.setNewCreatedTime(DateUtil.date());
        //获取商品sku的缩略图和商品相册
        if (productSkus != null && productSkus.size() > 0) {
            if (StringUtils.isNotBlank(productSkus.get(0).getPictures())) {
                @SuppressWarnings("rawtypes")
                List<Map> lists = JSONObject.parseArray(productSkus.get(0).getPictures(), Map.class);
                List<Map<String, Object>> list = new ArrayList<>();
                lists.forEach(vo -> {
                    Map<String, Object> map1 = new HashMap<>();
                    map1.put("img_original", (String) vo.get("PictureUrl"));
                    map1.put("thumb_url", vo.get("PictureThumbUrl"));
                    list.add(map1);
                });
                europeGood.setGallery(JSONObject.toJSONString(list));
                if (!CollectionUtils.isEmpty(lists)) {
                    europeGood.setGoodsImg((String) lists.get(0).get("PictureUrl"));
                }
            } else {
                europeGood.setGallery("");
                europeGood.setGoodsImg("");
            }
        } else {
            europeGood.setGallery("");
            europeGood.setGoodsImg("");
        }

        try {
            String oldCreatedTime = (String) map.get("CreatedTime");
            if (oldCreatedTime != null && StringUtils.isNotEmpty(oldCreatedTime)) {
                if (oldCreatedTime.endsWith("AM")) {
                    oldCreatedTime = oldCreatedTime.replace(" AM", "");
                    europeGood.setOldCreatedTime(new SimpleDateFormat("MM/dd/yyyy HH:mm:ss").parse(oldCreatedTime));//map.get("CreatedTime")
                } else {
                    oldCreatedTime = oldCreatedTime.replace(" PM", "");
                    europeGood.setOldCreatedTime(new SimpleDateFormat("MM/dd/yyyy HH:mm:ss").parse(oldCreatedTime));//map.get("CreatedTime")
                }
            } else {
                europeGood.setOldCreatedTime(null);
            }
            String oldModifyTime = (String) map.get("ModifyTime");
            if (oldModifyTime != null && StringUtils.isNotBlank(oldModifyTime)) {
                if (oldModifyTime.endsWith("AM")) {
                    oldModifyTime = oldModifyTime.replace(" AM", "");
                    europeGood.setOldModifyTime(new SimpleDateFormat("MM/dd/yyyy HH:mm:ss").parse(oldModifyTime));
                } else {
                    oldModifyTime = oldModifyTime.replace(" PM", "");
                    europeGood.setOldModifyTime(new SimpleDateFormat("MM/dd/yyyy HH:mm:ss").parse(oldModifyTime));
                }
            } else {
                europeGood.setOldModifyTime(null);
            }
        } catch (Exception e) {

        }
        return europeGood;
    }
    
    // Europe商品sku获取
    private EuropeProductSku getEuropeProductSku(int qty, EuropeProductSku europeProductSku, Map<String, Object> map, HashMap<String, Object> item, List<HashMap<String, Object>> stockList) {
        europeProductSku.setId((String) map.get("ID") + "-" + stockList.indexOf(item));
        europeProductSku.setGoodsId(Integer.parseInt((String) map.get("ID")));
        europeProductSku.setSuperColor((String) map.get("SuperColor"));
        europeProductSku.setColor((String) map.get("Color"));
        europeProductSku.setFabric((String) map.get("Fabric"));
        europeProductSku.setComposition((String) map.get("Composition"));
        europeProductSku.setSizeAndFit((String) map.get("SizeAndFit"));
        europeProductSku.setMadeIn((String) map.get("MadeIn"));

        if (StringUtils.isNotBlank(map.get("Pictures").toString())) {
            @SuppressWarnings("unchecked")
            List<HashMap<String, Object>> pictures = (List<HashMap<String, Object>>) map.get("Pictures");
            europeProductSku.setPictures(JSONObject.toJSONString(pictures));
        }
        if (StringUtils.isNotBlank(map.get("Stock").toString())) {
            @SuppressWarnings("unchecked")
            List<HashMap<String, Object>> stock = (List<HashMap<String, Object>>) map.get("Stock");
            europeProductSku.setStock(JSONObject.toJSONString(stock));
        }
        europeProductSku.setSize((String) item.get("Size"));
        europeProductSku.setQty(qty);
        europeProductSku.setSuk((String) map.get("Color") + "," + (String) item.get("Size"));
        String oldCreatedTime = (String) map.get("CreatedTime");
        try {
            if (oldCreatedTime != null && StringUtils.isNotEmpty(oldCreatedTime)) {
                if (oldCreatedTime.endsWith("AM")) {
                    oldCreatedTime = oldCreatedTime.replace(" AM", "");
                    europeProductSku.setOldCreatedTime(new SimpleDateFormat("MM/dd/yyyy HH:mm:ss").parse(oldCreatedTime));
                } else {
                    oldCreatedTime = oldCreatedTime.replace(" PM", "");
                    europeProductSku.setOldCreatedTime(new SimpleDateFormat("MM/dd/yyyy HH:mm:ss").parse(oldCreatedTime));
                }
            } else {
                europeProductSku.setOldCreatedTime(null);
            }
            String oldModifyTime = (String) map.get("ModifyTime");
            if (oldModifyTime != null && StringUtils.isNotBlank(oldModifyTime)) {
                if (oldModifyTime.endsWith("AM")) {
                    oldModifyTime = oldModifyTime.replace(" AM", "");
                    europeProductSku.setOldModifyTime(new SimpleDateFormat("MM/dd/yyyy HH:mm:ss").parse(oldModifyTime));
                } else {
                    oldModifyTime = oldModifyTime.replace(" PM", "");
                    europeProductSku.setOldModifyTime(new SimpleDateFormat("MM/dd/yyyy HH:mm:ss").parse(oldModifyTime));
                }
            } else {
                europeProductSku.setOldModifyTime(null);
            }
        } catch (ParseException e) {
            e.printStackTrace();
        }

        return europeProductSku;
    }

    // Buyer商品库存计算
    private Integer getBuyerStockByBarCode(String barCode, String sourceSkuId) {
        int stock = 0;
        try {
            BuyerProductResDTO buyerProductResDTO = getBuyerProductByBarCode(barCode);
            if(null == buyerProductResDTO || StringUtils.isEmpty(sourceSkuId)) {
                log.info("--------------- 查询buyer远程数据, 商品为空: {} 或参数缺失, sourceSkuId:{} ---------------", null == buyerProductResDTO, sourceSkuId);
                return stock;
            }
            List<Product> products = buyerProductResDTO.getProduct();
            if(CollectionUtils.isEmpty(products)) {
                log.info("--------------- 查询buyer远程数据, products为空, barCode:{}  ---------------", barCode);
                return stock;
            }
            List<ProductSku> productSkus = products.get(0).getSkus();
            if(CollectionUtils.isEmpty(productSkus)) {
                log.info("--------------- 查询buyer远程数据, productSkus为空, barCode:{}  ---------------", barCode);
                return stock;
            }
            for(ProductSku productSku : productSkus) {
                if(0 < productSku.getStock() && sourceSkuId.equals(productSku.getSkuId())) {
                    return productSku.getStock();
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        
        return stock;
    }
    
    // Europe商品库存计算
    private Integer getEuropeStockByBarCode(String barCode, String size) {
        int stock = 0;
        try {
            if(StringUtils.isEmpty(barCode) || 4 >= barCode.length()) {
                return stock;
            }
            String id = barCode.substring(4, barCode.length());
            
            List<EuropeProductSku> EuropeProductSkus = this.getEuropeProductSkus(id);
            if(CollectionUtils.isEmpty(EuropeProductSkus) || StringUtils.isEmpty(size)) {
                log.info("--------------- 查询Europe远程数据, 商品规格为空: {} 或参数缺失, size: {} ---------------", CollectionUtils.isEmpty(EuropeProductSkus), size);
                return stock;
            }

            for(EuropeProductSku productSku : EuropeProductSkus) {
                if(0 < productSku.getQty() && productSku.getSize().equals(size)) {
                    return productSku.getQty();
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        
        return stock;
    }
    
    // IM商品库存计算
    private Integer getImStockByBarCode(String barCode, String sourceSkuId,Integer buyStock) {
        int stock = 0;
        try {
            if(StringUtils.isEmpty(barCode) || 4 >= barCode.length()) {
                return stock;
            }
//            String id = barCode.substring(4, barCode.length());
            SystemConfig systemConfig = systemConfigService.getOne(Wrappers.<SystemConfig>lambdaQuery()
                    .eq(SystemConfig :: getName, Constants.IM_TOKEN)
                    .last("LIMIT 1")
                    );
            //根据itemId查询item信息
            ImItemResDTO imItemResDTO = this.getImItemInfo(Collections.singletonList(sourceSkuId),systemConfig);
//            ImProductResDTO imProductResDTO = this.getImProduct(Arrays.asList(id), systemConfig);
            // 判定token失效
            if(!imItemResDTO.getSuccess() && imItemResDTO.getError().contains("access-token")) {
                systemConfig = this.getImToken(systemConfig);
                imItemResDTO = this.getImItemInfo(Collections.singletonList(sourceSkuId),systemConfig);
            }
            List<ImItemDTO> imItemDTOs = imItemResDTO.getImItemDTOs();
            if(CollectionUtils.isNotEmpty(imItemDTOs)){
                ImItemDTO imItemDTO = imItemDTOs.get(0);
                if(imItemDTO.getStatus() != 1){
                    return stock;
                }
                if(imItemDTO.getStatus() == 1){
                    return imItemDTO.getQty();
                }
            }
//            List<ImProductDTO> imProductDTOs = imProductResDTO.getImProductDTOs();
//            if(CollectionUtils.isNotEmpty(imProductDTOs)) {
//                List<ImProductItemDTO> items = imProductDTOs.get(0).getItems();
//                if(CollectionUtils.isNotEmpty(items)) {
//                    for(ImProductItemDTO item : items) {
//                        if(sourceSkuId.equals(item.getItemId())) {
//                            return item.getQty();
//                        }
//                    }
//                }
//            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        
        return buyStock;
    }

    // XYY商品库存计算
    private Integer getXyyStockByBarCode(String barCode, String sourceSkuId) {
    	int stock = 0;
    	try {
    		if(StringUtils.isEmpty(barCode) || 4 >= barCode.length()) {
    			return stock;
    		}
    		String id = barCode.substring(4, barCode.length());
    		String[] sourceSkus = sourceSkuId.split("-");
    		long time = System.currentTimeMillis();
    		List<XyyProductSkuResDTO> xyyProductSkuResDTOs = this.getXyySkus(Integer.parseInt(id), time, getXyyToken(time));
    		if(CollectionUtils.isEmpty(xyyProductSkuResDTOs)) {
    			return stock;
    		}
			for(XyyProductSkuResDTO item : xyyProductSkuResDTOs) {
				if(sourceSkus[0].equals(item.getSpecId())) {
					List<TStorhouse> tStorhouses = item.getTStorhouses();
					for(TStorhouse tStorhouse : tStorhouses) {
						if(sourceSkus[1].equals(tStorhouse.getShId())) {
							return tStorhouse.getXianhuoStock();
						}
					}
				}
			}
    	} catch (Exception e) {
    		e.printStackTrace();
    	}
    	
    	return stock;
    }

    // 签名
    private String getSignature(String timestamp, String random) {
        Map<String, String> signMap = MapUtil.newHashMap(4);
        signMap.put("timeStamp", timestamp);
        signMap.put("randomStr", random);
        signMap.put("appkey", this.buyAppKey);
        signMap.put("appsecret", this.buyAppSecret);

        List<String> valueList = signMap.entrySet().stream().sorted(Map.Entry.comparingByValue()).map(Map.Entry::getValue).collect(Collectors.toList());
        String signStr = StringUtils.join(valueList, null);
        signStr = DigestUtil.sha1Hex(signStr);
        signStr = DigestUtil.md5Hex(signStr);
        signStr = DigestUtil.md5Hex(signStr);

        return signStr.toUpperCase();
    }
    
    /******************* IM ********************/
    /**
     * 查询im分页商品数据
     * @Description:  
     * @author daigb 
     * @param @param pageNow
     * @param @param pageSize
     * @param @return
     * @param @throws Exception
     * @return InProductResDTO
     * @throws
     */
    public ImProductResDTO getImProduct(List<String> ids, SystemConfig systemConfig) throws Exception {
        RestTemplate restTemplate = restTemplateConfig.restTemplate();
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        headers.add("access_token", systemConfig.getValue());
        headers.add("x-forwarded-for", "183.128.136.165");
        JSONObject param = new JSONObject();
        param.put("productIds", ids);
        HttpEntity<JSONObject> formEntity = new HttpEntity<>(param, headers);
        ResponseEntity<String> response = restTemplate.postForEntity(this.imDomainUrl + this.imInfoUrl, formEntity , String.class);
        ObjectMapper mapper = new ObjectMapper();
        ImProductResDTO imProductResDTO = mapper.readValue(response.getBody(), ImProductResDTO.class);
        if(HttpStatus.OK != response.getStatusCode()) {
            JSONObject message = JSONObject.parseObject(response.getBody());
            String errorMessage = message.getString("error");

            log.info("--------------- {} ---------------", errorMessage);
        }
        
        return imProductResDTO;
    }

    /**
     * im根据productID查询商品信息。
     * @param ids
     * @param systemConfig
     * @return
     * @throws Exception
     */
    public ImProductInfoResDTO getImProductInfo(List<String> ids, SystemConfig systemConfig) throws Exception {
        RestTemplate restTemplate = restTemplateConfig.restTemplate();
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        headers.add("access-token", systemConfig.getValue());
        headers.add("x-forwarded-for", "121.4.132.191");
        JSONObject param = new JSONObject();
        param.put("productIds", ids);
        HttpEntity<JSONObject> formEntity = new HttpEntity<>(param, headers);
        ResponseEntity<String> response = restTemplate.postForEntity(this.imDomainUrl + this.imProductInfoUrl, formEntity , String.class);
        ObjectMapper mapper = new ObjectMapper();
        ImProductInfoResDTO imProductInfoResDTO = mapper.readValue(response.getBody(), ImProductInfoResDTO.class);
        if(HttpStatus.OK != response.getStatusCode()) {
            JSONObject message = JSONObject.parseObject(response.getBody());
            String errorMessage = message.getString("error");
            log.info("--------------- {} ---------------", errorMessage);
        }
        return imProductInfoResDTO;
    }


    /**
     * im根据itemID查询item信息。
     * @param itemIdList
     * @param systemConfig
     * @return
     * @throws Exception
     */
    public ImItemResDTO getImItemInfo(List<String> itemIdList, SystemConfig systemConfig) throws Exception {
        RestTemplate restTemplate = restTemplateConfig.restTemplate();
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        headers.add("access-token", systemConfig.getValue());
        headers.add("x-forwarded-for", "121.4.132.191");
        JSONObject param = new JSONObject();
        param.put("itemIds", itemIdList);
        HttpEntity<JSONObject> formEntity = new HttpEntity<>(param, headers);
        ResponseEntity<String> response = restTemplate.postForEntity(this.imDomainUrl + this.imItemInfoUrl, formEntity , String.class);
        ObjectMapper mapper = new ObjectMapper();
        ImItemResDTO imItemResDTO = mapper.readValue(response.getBody(), ImItemResDTO.class);
        if(HttpStatus.OK != response.getStatusCode()) {
            JSONObject message = JSONObject.parseObject(response.getBody());
            String errorMessage = message.getString("error");
            log.info("--------------- {} ---------------", errorMessage);
        }
        return imItemResDTO;
    }
    
    // 获取Im token
    public SystemConfig getImToken(SystemConfig systemConfigParam) {
        SystemConfig systemConfig = systemConfigService.getOne(Wrappers.<SystemConfig>lambdaQuery()
                .eq(SystemConfig :: getName, Constants.IM_TOKEN)
                .last("LIMIT 1")
                );
        // token已被更新
        if(systemConfig.getFormId().intValue() != systemConfigParam.getFormId().intValue()) {
            return systemConfig;
        }
        
        RestTemplate restTemplate = restTemplateConfig.restTemplate();
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        // TODO 待删除
        headers.add("x-forwarded-for", "121.4.132.191");
        JSONObject param = new JSONObject();
        param.put("appKey", this.imAppKey);
        param.put("appSecret", this.imAppSecret);
        HttpEntity<JSONObject> formEntity = new HttpEntity<>(param, headers);
        ResponseEntity<String> response = restTemplate.postForEntity(this.imDomainUrl + this.imTokenUrl, formEntity , String.class);

        log.info("--------------- IM授权获取token返回: {} ---------------", response);
        if(HttpStatus.OK == response.getStatusCode()) {
            String token = JSONObject.parseObject(response.getBody()).getJSONObject("data").getString("access_token");
            systemConfigParam.setValue(token);
            systemConfigParam.setFormId(systemConfigParam.getFormId() + 1);
            systemConfigParam.setUpdateTime(new Date());
            systemConfigService.updateById(systemConfigParam);
        }
        
        return systemConfigParam;
    }
    /******************* end ********************/
    
    /******************* xyy ********************/
    /**
     * 获取商品sku
     * @Description:  
     * @author daigb 
     * @param @param ids
     * @param @return
     * @param @throws Exception
     * @return InProductResDTO
     * @throws
     */
     public List<XyyProductSkuResDTO> getXyySkus(Integer goodsId, Long time, String token) throws Exception {
         // 组装请求url
         StringBuilder sb = new StringBuilder();
         sb.append(xyyUrl);
         sb.append("/getGoodsStock/t/");
         sb.append(time);
         sb.append("/r/");
         sb.append(time);
         sb.append("/appkey/");
         sb.append(xyyAppKey);
         sb.append("/secret/");
         sb.append(xyyAppSecret);
         sb.append("/s/");
         sb.append(token);
         sb.append("/gid/");
         sb.append(goodsId);
         // 发送请求
         RestTemplate restTemplate = restTemplateConfig.restTemplate();
         ResponseEntity<String> response = restTemplate.getForEntity(sb.toString(), String.class);
         if (HttpStatus.OK != response.getStatusCode()) {
             JSONObject message = JSONObject.parseObject(response.getBody());
             String errorMessage = message.getString("error");

             log.info("--------------- {} ---------------", errorMessage);
         }
         
         ObjectMapper mapper = new ObjectMapper();
         JavaType javaType = mapper.getTypeFactory().constructParametricType(ArrayList.class, XyyProductSkuResDTO.class);
         List<XyyProductSkuResDTO> xyyProductSkuResDTOs = mapper.readValue(response.getBody(), javaType);

         return xyyProductSkuResDTOs;
	}
    
    public String getXyyToken(long time) {
        // 生成秘钥
        String sign = DigestUtils.sha1Hex(time + "" + time + xyyAppKey + xyyAppSecret);
        sign = DigestUtils.md5Hex(sign);
        sign = DigestUtils.md5Hex(sign);
        sign = sign.toUpperCase();
        return sign;
    }
    
    /******************* end ********************/

    public LeamProductResDTO getLeamByProductId(int productId) throws JsonProcessingException {
        StringBuilder sb = new StringBuilder();
        sb.append(leamUrl)
                .append("/ApiV3/token/")
                .append(leamToken)
                .append("/callType/singleProductCheck/productID/")
                .append(productId);
        RestTemplate restTemplate = restTemplateConfig.restTemplate();
        ResponseEntity<String> response = restTemplate.getForEntity(sb.toString(), String.class);
        if (HttpStatus.OK != response.getStatusCode()) {
            JSONObject message = JSONObject.parseObject(response.getBody());
            String errorMessage = message.getString("error");
            log.info("--------------- {} ---------------", errorMessage);
        }
        ObjectMapper mapper = new ObjectMapper();
        LeamProductResDTO leamProductResDTO = mapper.readValue(response.getBody(), LeamProductResDTO.class);
        return leamProductResDTO;
    }

    public String selectImageUrl(){
        //组装请求url
        StringBuilder sb = new StringBuilder();sb.append(leamUrl)
                .append("/ApiV3/token/")
                .append(leamToken);
        // 发送请求
        RestTemplate restTemplate = restTemplateConfig.restTemplate();
        ResponseEntity<String> response = restTemplate.getForEntity(sb.toString(), String.class);
        if (HttpStatus.OK != response.getStatusCode()) {
            JSONObject message = JSONObject.parseObject(response.getBody());
            String errorMessage = message.getString("error");
            log.info("--------------- {} ---------------", errorMessage);
        }
        JSONObject message = JSONObject.parseObject(response.getBody());
        return message.getString("image_url");
    }

    public int getLeamSku(String sourceSkuId) {
        StringBuilder sb = new StringBuilder();sb.append(leamUrl)
                .append("/ApiV3/token/")
                .append(leamToken)
                .append("/callType/singleStockCheck/stockID/")
                .append(sourceSkuId);
        RestTemplate restTemplate = restTemplateConfig.restTemplate();
        ResponseEntity<String> response = restTemplate.getForEntity(sb.toString(), String.class);
        if (HttpStatus.OK != response.getStatusCode()) {
            JSONObject message = JSONObject.parseObject(response.getBody());
            String errorMessage = message.getString("error");
            log.info("--------------- {} ---------------", errorMessage);
        }
        JSONObject sku = JSONObject.parseObject(response.getBody());
        JSONArray jsonArray = sku.getJSONArray("products");
        Object qty = jsonArray.getJSONObject(0).get("qty");
        return Integer.parseInt(qty.toString());
    }

    /**
     * 获取收货时间
     * @param stockArea 发货地类型
     * @param isEurope 商品来源
     * @param merId 商户id
     * @param productId 商品id
     * @return 收货时间
     */
    public String getReceivingTime(Integer stockArea,Integer isEurope,Integer merId,Integer productId){
        if(Objects.equals(isEurope,ProductTypeEnum.ORANGE.getCode())){
            String arrivalDays = OrangeChannelTypeEnum.valueOf(stockArea).getArrivalDays();
            return "约"+arrivalDays+"个工作日到货";
        }
        //自建商品 自定义收货时间
        if(Objects.equals(isEurope,ProductTypeEnum.INSIDE.getCode())){
            MybatisPlusConfig.tableNameMp.set(TableNameUtil.getProductMerName(merId));
            StoreProductMer mer = storeProductMerService.getOne(Wrappers.<StoreProductMer>lambdaQuery()
            		.eq(StoreProductMer::getProductId, productId)
            		);
            return Objects.isNull(mer) ?  "约7-15个工作日到货" : "约"+mer.getEarliestArrivalData()+"-"+mer.getSlowestArrivalData()+"个工作日到货";
        }
        String receivingTime = null;
        switch(stockArea){
            case 1:
                receivingTime = systemConfigService.getOne(Wrappers.lambdaQuery(SystemConfig.class).eq(SystemConfig::getName,Constants.SYSTEM_CONFIG_CN_RECEIVING_TIME)).getTitle();
                break;
            case 2:
                receivingTime = systemConfigService.getOne(Wrappers.lambdaQuery(SystemConfig.class).eq(SystemConfig::getName,Constants.SYSTEM_CONFIG_HK_RECEIVING_TIME)).getTitle();
                break;
            case 3:
                receivingTime = systemConfigService.getOne(Wrappers.lambdaQuery(SystemConfig.class).eq(SystemConfig::getName,Constants.SYSTEM_CONFIG_EUR_RECEIVING_TIME)).getTitle();
                break;
        }
        return StringUtils.isNotBlank(receivingTime) ? receivingTime : "约25-30个工作日到货";
//        return receivingTime;
    }

    /**
     * 获取发货时间
     * @param tempId 发货地
     * @param isEurope 商品来源
     * @param merId 商户id
     * @param productId 商品id
     * @return 发货时间
     */
    public String getDeliveryTimeByTempId(Integer tempId,Integer isEurope,Integer merId,Integer productId){
        //橙子商品
        if(Objects.equals(isEurope,ProductTypeEnum.ORANGE.getCode())){
            String deliverDays = OrangeChannelTypeEnum.valueOf(tempId).getDeliverDays();
            return "预计"+deliverDays+"个工作日发货";
        }
        //自建商品 自定义收货时间
        if(Objects.equals(isEurope, ProductTypeEnum.INSIDE.getCode())){
            MybatisPlusConfig.tableNameMp.set(TableNameUtil.getProductMerName(merId));
            StoreProductMer mer = storeProductMerService.getOne(Wrappers.<StoreProductMer>lambdaQuery()
            		.eq(StoreProductMer::getProductId, productId)
            		);
            return Objects.isNull(mer) ?  "预计2个工作日发货" : "预计"+mer.getDeliveryData()+"个工作日发货";
        }
        return Objects.equals(tempId, StockAreaTempEnum.EUR.getTempId()) ? systemConfigService.getValueByKey(Constants.SYSTEM_CONFIG_EUR_DELIVERY_TIME)
                : systemConfigService.getValueByKey(Constants.SYSTEM_CONFIG_HK_DELIVERY_TIME);
    }

    /**
     * 公共验签方法
     * @Description:  
     * @author daigb 
     * @param @return
     * @return String
     * @throws
     */
    public static String getSign(String millis, String merNo, String merSecret) {
        String sign = DigestUtils.sha1Hex(millis + merNo + merSecret);
        sign = DigestUtils.md5Hex(sign);
        sign = DigestUtils.md5Hex(sign);
        sign = sign.toUpperCase();
        return sign;
    }
    
    public void getChannelMerchantAuth(LambdaQueryWrapper<StoreProduct> lambdaQueryWrapper, Integer merId) {
        ChannelMerchant channelMerchant = channelMerchantService.getById(merId);
        if (ObjectUtils.isNotEmpty(channelMerchant)) {
            Supplier supplier = supplierService.getSupplierBarcode(merId);
            List<String> brandIdsList = JSON.parseArray(channelMerchant.getBrandIds(), String.class);
            List<String> suppliersIdList = JSON.parseArray(channelMerchant.getSuppliersIds(), String.class);
            List<String> tempIdList = JSON.parseArray(channelMerchant.getTempId(), String.class);
            if (CollectionUtils.isNotEmpty(brandIdsList)) {
                lambdaQueryWrapper.in(StoreProduct::getBrandId, brandIdsList);
            }
            if (CollectionUtils.isNotEmpty(suppliersIdList)) {
                if (null != supplier) {
                    //商户如果是供应商的话 查询商户自建的商品 默认传入商户配置的供应商id
                    suppliersIdList.add(supplier.getId().toString());
                }
                lambdaQueryWrapper.in(StoreProduct::getSuppliersId, suppliersIdList);
            }
            if (CollectionUtils.isNotEmpty(tempIdList)) {
                lambdaQueryWrapper.in(StoreProduct::getTempId, tempIdList);
            }
        }
    }
    public void getChannelMerchantAuthV2(StoreProductQueryDTO storeProductQueryDTO, Integer merId) {
        ChannelMerchant channelMerchant = channelMerchantService.getById(merId);
        if (ObjectUtils.isNotEmpty(channelMerchant)) {
            Supplier supplier = supplierService.getSupplierBarcode(merId);
            List<String> brandIdsList = JSON.parseArray(channelMerchant.getBrandIds(), String.class);
            List<String> suppliersIdList = JSON.parseArray(channelMerchant.getSuppliersIds(), String.class);
            List<String> tempIdList = JSON.parseArray(channelMerchant.getTempId(), String.class);
            if (CollectionUtils.isNotEmpty(brandIdsList)) {
                storeProductQueryDTO.setBrandIdsList(brandIdsList);
            }
            if (CollectionUtils.isNotEmpty(suppliersIdList)) {
                if (null != supplier) {
                    //商户如果是供应商的话 查询商户自建的商品 默认传入商户配置的供应商id
                    suppliersIdList.add(supplier.getId().toString());
                }
                storeProductQueryDTO.setSuppliersIdList(suppliersIdList);
            }
            if (CollectionUtils.isNotEmpty(tempIdList)) {
                storeProductQueryDTO.setTempIdList(tempIdList);
            }
        }
    }

    //判断商品运费模板信息
    public Boolean checkShippingTemp(StoreProduct product) {

        //2023.6.2判断运费模板信息
        //如果是自建商品
        if(product.getIsEurope() == 1 && ObjectUtil.isNull(product.getShippingTempId())){
            return  false;
        }

        //发货地国内的云仓商品
        if(StockAreaTempEnum.CN.getTempId().equals(product.getTempId()) && product.getIsEurope() != 1 ){

            //商户商品判断
            StoreProductMer merProduct = storeProductMerService.getOne(Wrappers.<StoreProductMer>lambdaQuery()
                    .eq(StoreProductMer :: getProductId, product.getId())
            );

            // if(ObjectUtil.isNotNull(merProduct) && ObjectUtil.isNull(merProduct.getShippingTempId())){
            if(ObjectUtil.isNull(merProduct) || ObjectUtil.isNull(merProduct.getShippingTempId())){
                return  true;
            }

            if(ObjectUtil.isNotNull(merProduct.getShippingTempId())){

                ShippingTemplates shippingTemplate = shippingTemplatesService.getById(merProduct.getShippingTempId());

                if(ObjectUtil.isNotNull(shippingTemplate)) {

                    if (shippingTemplate.getType() == 2) {  //重量

                        //获取商品的数据
                        StoreProductAttrValue storeProductAttrValue = storeProductAttrValueService.getOne(Wrappers.<StoreProductAttrValue>lambdaQuery()
                                .eq(StoreProductAttrValue::getProductId, product.getId())
                                .isNull(StoreProductAttrValue::getWeight)
                                .last("LIMIT 1"));

                        if (ObjectUtil.isNotNull(storeProductAttrValue)) {
                            return false;
                        }

                    } else if (shippingTemplate.getType() == 3) {   //体积

                        //获取商户商品的数据
                        StoreProductValueMer storeProductValueMer = storeProductValueMerService.getOne(Wrappers.<StoreProductValueMer>lambdaQuery()
                                .eq(StoreProductValueMer::getProductId, product.getId())
                                .isNull(StoreProductValueMer::getVolume)
                                .last("LIMIT 1"));

                        if (ObjectUtil.isNotNull(storeProductValueMer)) {
                            return false;
                        }

                    }
                }else
                {
                    return false;
                }
            }else
            {
                return false;
            }

        }

        return  true;
    }

    //判断是否在使用运费模板
    public Boolean checkShippingTempUsed(Integer tempId) {

        //如果是自建商品 有商品使用
        List<StoreProduct> storeProductList = storeProductService.list
                (Wrappers.lambdaQuery(StoreProduct.class)
                        .eq(StoreProduct::getShippingTempId, tempId)
                        .eq(StoreProduct::getIsShow, 1)
                );

        if (CollectionUtils.isNotEmpty(storeProductList)) {
            return  true;
        }

        //云仓商品
        List<StoreProductMer> storeProductMerList  = storeProductMerService.list(Wrappers.<StoreProductMer>lambdaQuery()
                .eq(StoreProductMer :: getShippingTempId, tempId)
                .eq(StoreProductMer::getIsNotShow, 0)
        );
        if (CollectionUtils.isNotEmpty(storeProductMerList)) {
            return  true;
        }

        return  false;
    }

}
